/*
 * Copyright (C) 2010 The Android Open Source Project 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */

package org.lhlzi.ithink;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import org.lhlzi.ithink.model.RecentContact;
import org.lhlzi.ithink.model.RecentEvent;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class IphoneCallLogDetails extends Activity {
	
	public final static String TAG = IphoneCallLogDetails.class.toString();
	
	public final static String ACTION = "org.lhlzi.ithink.RECENT_DETAIL";
	
	private static RecentContact recentContact = null;
	private static DataCacheWrapper dataCacheWrapper = null;

	public static final String KEY_OUTGOING = "outgoing";
	public static final String KEY_INCOMING = "incoming";
	public static final String KEY_MISSED   = "missed";
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
		setContentView(R.layout.recent_detail);
		
		((TextView)findViewById(R.id.recents_back)).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		fillViewsContent();
	}
	
	
	public static void showActivity(Context context, RecentContact contact, DataCacheWrapper dataCache) {
		recentContact = contact;
		dataCacheWrapper = dataCache;
		context.startActivity(new Intent(ACTION));
	}
	
	private void fillViewsContent() {
		
		if (recentContact == null) {
			throw new NullPointerException("The RecentContact object is null.");
		}
		
		if (recentContact.hasContactInfo()) {
			Log.i(TAG,"Research contact info,[hasContactInfo=" + recentContact.hasContactInfo()+"]");
			Bitmap contactPhoto = RecentWidgetUtils.CONTACTS_API.loadContactPhoto(this, recentContact);
			if (contactPhoto != null) {
				((ImageView)findViewById(R.id.contact_logo)).setImageBitmap(contactPhoto);
				
				Log.i(TAG, "Find contact photo from database.");
			}
		
		}
		
		String displayName = recentContact.getDisplayName();
		
		if (displayName != null) {
			((TextView)findViewById(R.id.display_name)).setText(
					Utils.isnumber(displayName)? Utils.formatNumber(displayName) : displayName);
		}
		
		displayName = recentContact.getDisplayLabel();
		
		if (displayName != null) {
			((TextView)findViewById(R.id.contact_label)).setText(displayName);
		}
		
		String displayNumber = recentContact.getNumber();
		
		if (displayNumber != null) {
			
			TextView contactNumber = (TextView)findViewById(R.id.contact_number);
			contactNumber.setText(Utils.formatNumber(displayNumber));
			contactNumber.setOnClickListener(contactNumberButtonListener);
			
			if (dataCacheWrapper != null ) {
				
				String location = dataCacheWrapper.revealNumber(displayNumber);
				
				((TextView)findViewById(R.id.contact_location_display)).setText(location);
			}
			
		}		
		
		TableLayout table = (TableLayout)findViewById(R.id.calllog_detail);
		List<RecentEvent> callLogs = recentContact.getRecentEvents();
		
		boolean hasFirst = buildRows(callLogs, RecentEvent.SUBTYPE_INCOMING,false, table);
		
		hasFirst = buildRows(callLogs, RecentEvent.SUBTYPE_OUTGOING,hasFirst, table);
		
		buildRows(callLogs, RecentEvent.SUBTYPE_MISSED,hasFirst, table);
		
		//Log.i(TAG, "Track the fucking string," + getString(R.string.calllog_detail_date));
		

	}
	
	private boolean buildRows(List<RecentEvent> recentEvents, int callType, 
			boolean hasFirst, TableLayout table) {
		
		int size = recentEvents.size();
		RecentEvent recent = null;
		String callTypeString = null;
		
		TableRow row = new TableRow(this);
		
		boolean existing = false;
		
		switch(callType) {
		case RecentEvent.SUBTYPE_INCOMING:
			callTypeString = getString(R.string.calllog_incoming_string);
			break;
		case RecentEvent.SUBTYPE_OUTGOING:
			callTypeString = getString(R.string.calllog_outgoing_string);
			break;
		case RecentEvent.SUBTYPE_MISSED:
			callTypeString = getString(R.string.calllog_missed_string);
			break;
		}
		
		for (int i=0; i<size; i++) {
			
			recent = recentEvents.get(i);
			if (recent.getSubType() != callType) {
				continue;
			}
			
			if (!existing) {
				makeColumns(row,
						callTypeString, 
						R.style.recent_detail_call_log_area,
						2,
						-1);
				//Log.i(TAG, "Title has been setted.");
				
				if (!hasFirst) {
					makeColumns(row,
							DateFormat.format(getString(R.string.calllog_date), recent.getDate()), 
							R.style.recent_detail_call_log_area,
							0,
							-1);
					//Log.i(TAG, "Title time has been setted,this is first.");
					
					hasFirst = true;
				}
				
				table.addView(row);
				
				existing = true;
			}
			
			row = new TableRow(this);
			
			
			makeColumns(row,
					DateFormat.format(getString(R.string.calllog_detail_date), recent.getDate()),
					R.style.calllog_detail,
					1,
					Gravity.RIGHT);
			if (recent.getSubType() != RecentEvent.SUBTYPE_MISSED)
				makeColumns(row,
						formatTime(recent.getDuration()),
						R.style.calllog_detail,
						1,
						Gravity.CENTER);
			
			table.addView(row);
			
			//Log.i(TAG, "Details is setting...");
		}
		
		return hasFirst;
		
	}
	
	private TableRow makeColumns(TableRow row, CharSequence text, 
			int appearance, int span, int gravity) {
		
		TextView view = new TextView(this);
		view.setText(text);
		if (appearance > 0)
			view.setTextAppearance(this, appearance);
		
		TableRow.LayoutParams params = new TableRow.LayoutParams(
				TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
		
		params.span = span > 0 ? span : 1;
		
		if (gravity >= 0) {
			view.setGravity(gravity);
		}
		
		row.addView(view, params);
		
		return row;
	}
	
	public static Spanned formatTime(long times) {
		int mins = 0;
		int seconds = 0;
		if (times > 60) {
			seconds = (int)times % 60;
			mins = (int)times / 60;
		} else seconds = (int)times;
		
		StringBuilder timeCal = new StringBuilder();
		
		if (mins == 1) {
			
			if (seconds > 0) {			
				timeCal.append(mins);
				timeCal.append("&nbsp;min&nbsp;");
				timeCal.append(seconds);
				timeCal.append("&nbsp;secs");
			} else {
				timeCal.append(mins);
				timeCal.append("&nbsp;minute&nbsp;");
			}
		} else if (mins > 1) {
			if (seconds > 0) {
				timeCal.append(mins);
				timeCal.append("&nbsp;mins&nbsp;");
				timeCal.append(seconds);
				timeCal.append("&nbsp;secs");
			} else {
				timeCal.append(mins);
				timeCal.append("&nbsp;minutes&nbsp;");
			}
		} else {
			timeCal.append(seconds);
			timeCal.append("&nbsp;seconds");
		}
		
		return Html.fromHtml(timeCal.toString());
	}
	
	protected View.OnClickListener contactNumberButtonListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			
			callNumber(recentContact.getNumber());
		}
	};
	
	public void callNumber(String number) {
		Intent intent = new Intent(Intent.ACTION_CALL);
		intent.setData(Uri.parse("tel:" + number));
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(intent);
	}
}
